package com.kyxx.topics.activity;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.bean.ArticleBean;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.TimeUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public class SearchActivity extends BaseActivity {
    private EditText et_seach;
    private ImageView iv_search;
    private Button btn_certain_cancel;
    private TextView tv_seach;
    private int lastVisiblePosition;
    private int pageSize = 1;
    private int countSize = 10;
    private List<ArticleBean> articleBeanList = new ArrayList<>();
    SearchAdapter searchAdapter;
    private ListView lv;
private Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what){

        }
    }
};
    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_search);
        BaseApp.getInstance().addActivity(this);
    }

    @Override
    protected void findViewById() {
        et_seach = (EditText) findViewById(R.id.et_seach);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        btn_certain_cancel = (Button) findViewById(R.id.btn_certain_cancel);
        tv_seach = (TextView) findViewById(R.id.tv_seach);
        lv = (ListView) findViewById(R.id.lv);
    }

    @Override
    protected void setListener() {
        tv_seach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initList(Constants.INITDATA, pageSize, countSize);
                tv_seach.setVisibility(View.GONE);
            }
        });
        btn_certain_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_seach.setText("");
            }
        });
        et_seach.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(et_seach.getText())) {
                    iv_search.setVisibility(View.GONE);
                    tv_seach.setVisibility(View.GONE);
                    tv_seach.setText("");
                } else {
                    iv_search.setVisibility(View.VISIBLE);
                    tv_seach.setVisibility(View.VISIBLE);
                    tv_seach.setText("搜索“" + et_seach.getText() + "”");
                }
            }
        });
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (lastVisiblePosition == lv.getLastVisiblePosition())
                    return;
                lastVisiblePosition = lv.getLastVisiblePosition();
                Log.e("topic", lastVisiblePosition + "onScroll" + lv.getCount());
                if (lastVisiblePosition == lv.getCount() - 2 && lv.getCount() >= countSize) {
                    pageSize++;
                    initList(Constants.LOADMORE, pageSize, countSize);
                }

            }
        });
    }

    @Override
    protected void processLogic() {
        searchAdapter = new SearchAdapter();
        lv.setAdapter(searchAdapter);
    }

    class SearchAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return articleBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return articleBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(context, R.layout.item_zhuanti, null);
                holder.iv_zhuanti = (ImageView) view.findViewById(R.id.iv_zhuanti);
                holder.tv_title = (TextView) view.findViewById(R.id.tv_title);
                holder.tv_day = (TextView) view.findViewById(R.id.tv_day);
                holder.iv_focus = (ImageView) view.findViewById(R.id.iv_focus);
                holder.tv_num = (TextView) view.findViewById(R.id.tv_num);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            if (articleBeanList.get(i).getImgurl() != null) {
                imageLoader.displayImage(UrlUtils.BASEHTTP + articleBeanList.get(i).getImgurl().getPath(), holder.iv_zhuanti, options);
            } else {
                imageLoader.displayImage("", holder.iv_zhuanti, options);
            }
            holder.tv_title.setText(articleBeanList.get(i).getTitle());
            holder.tv_day.setText(TimeUtils.milliseconds2String(Long.valueOf(articleBeanList.get(i).getCreate_time()) * 1000, new SimpleDateFormat("MM-dd HH:mm")));
            holder.tv_num.setText(articleBeanList.get(i).getComment());
            return view;
        }
    }

    class ViewHolder {
        private ImageView iv_zhuanti;
        private TextView tv_title;
        private TextView tv_day;
        private ImageView iv_focus;
        private TextView tv_num;
    }

    private void initList(final int type, int page, final int count) {
        RequestParams params = new RequestParams();
        params.put("name", et_seach.getText());
        params.put("p", page);
        params.put("rows", count);
        RestClient.get(UrlUtils.SEARCH + "&name=" + et_seach.getText() + "&p=" + page + "&rows=" + count, this, new ResponseListener(this, true) {
            @Override
            public void success(int arg0, Header[] arg1, org.json.JSONObject result) {
                et_seach.setText("");
                try {
                    switch (type) {
                        case Constants.INITDATA:
                            articleBeanList = JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class);
                            searchAdapter = new SearchAdapter();
                            lv.setAdapter(searchAdapter);
                            break;
                        case Constants.LOADMORE:
                            articleBeanList.addAll(JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class));
                            searchAdapter.notifyDataSetChanged();
                            break;
                        case Constants.REFRESH:
                            articleBeanList = JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class);
                            searchAdapter = new SearchAdapter();
                            lv.setAdapter(searchAdapter);
                            break;
                    }
                    lastVisiblePosition = lv.getLastVisiblePosition();
                } catch (JSONException e) {
                    ToastUtils.show(context,"没有您想搜的~~");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });

    }
}
